﻿using System;
using System.Configuration;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;

namespace KMS.Core
{
    public class Kernel
    {
        /// <summary>
        /// 默认， 数据库链接名
        /// </summary>
        public const string DEFAULT_CONN = "SqlConn";

        private static string _DEFAULT_CONNECTSTRING = string.Empty;
        public static string DEFAULT_CONNECTSTRING
        {
            get
            {
                if (string.IsNullOrEmpty(_DEFAULT_CONNECTSTRING))
                {
                    try
                    {
                        _DEFAULT_CONNECTSTRING = ConfigurationManager.ConnectionStrings[DEFAULT_CONN].ConnectionString;
                    }
                    catch (Exception)
                    { 
                        _DEFAULT_CONNECTSTRING = string.Empty;
                    }
                    
                }
                return _DEFAULT_CONNECTSTRING;
            }
            set
            {
                _DEFAULT_CONNECTSTRING = value;
            }
        }

        private static ConnectstringData _data = new ConnectstringData();
        public  static ConnectstringData Connectstring 
        {
            get { return _data; }
        }
    }

    public class ConnectstringData
    {
        private ConcurrentDictionary<string, string> data = new ConcurrentDictionary<string, string>();

        public string this[string key]
        {
            get
            {
                
                string result;
                if (data.TryGetValue(GetKey(key), out result))
                {
                    return result;
                }
                else
                {
                    result = ConfigurationManager.ConnectionStrings[GetKey(key)].ConnectionString; 
                }

                return result;
            }
            set
            { 
                data[GetKey(key)] = value;
            }
        }

        private string GetKey(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                key = Kernel.DEFAULT_CONN;
            }
            return key;
        }
    }
}
